import { _decorator, Node, Rect, Sprite, SpriteFrame, UITransform, Vec3 } from 'cc';
import { ListRender } from '../../Basic/Component/ListRender';
import { autoComp } from '../../Basic/Manager/BaseManager';
import { RoleEnemy } from './RoleEnemy';
import { MainModel_Ins } from './MainModel';
import { TreeItem } from './TreeItem';
import { WeaponAtkValue } from '../Config/ConstData';

const { ccclass, property } = _decorator;
@ccclass('WeaponItem')
export class WeaponItem extends ListRender {
  @autoComp(Sprite)
  item: Sprite;
  @autoComp(UITransform, 'item')
  itemTrans: UITransform;
  data: number;

  hitEnemyArr: string[] = [];
  hitTreeArr: string[] = [];
  dataChanged(...args: unknown[]): void {
    MainModel_Ins.loadDynamicRes<SpriteFrame>(`resources/sprite/weapon_${this.data}/spriteFrame`).then((spr) => {
      this.item.spriteFrame = spr;
    });
  }

  checkWoodHit(treeArr: TreeItem[]) {
    const lPos = this.node.getWorldPosition();
    const treeParent = MainModel_Ins.basePanel.mapNode;
    const treeTrans = treeParent.getComponent(UITransform);
    treeTrans.convertToNodeSpaceAR(lPos, lPos);
    treeArr.forEach((tree) => {
      const treePos = tree.node.getPosition().clone();
      const space = new Vec3(treePos.x - lPos.x, treePos.y - lPos.y, 0);
      if (space.length() <= 100) {
        if (this.hitTreeArr.indexOf(tree.node.uuid) === -1) {
          this.hitTreeArr.push(tree.node.uuid);
          tree.hirt();
        }
      } else if (this.hitTreeArr.indexOf(tree.node.uuid) !== -1) {
        this.hitTreeArr.splice(this.hitTreeArr.indexOf(tree.node.uuid), 1);
      }
    });
  }

  checkEnemyHit(enemyArr: RoleEnemy[]) {
    // 距离判断
    const lPos = this.node.getWorldPosition();
    const enemyParent = MainModel_Ins.basePanel.mapNode;
    const enemyTrans = enemyParent.getComponent(UITransform);
    enemyTrans.convertToNodeSpaceAR(lPos, lPos);
    enemyArr.forEach((enemy) => {
      const enemyPos = enemy.node.getPosition().clone();
      const space = new Vec3(enemyPos.x - lPos.x, enemyPos.y - lPos.y, 0);
      if (space.length() <= 100) {
        if (this.hitEnemyArr.indexOf(enemy.node.uuid) === -1) {
          this.hitEnemyArr.push(enemy.node.uuid);
          enemy.hirt(WeaponAtkValue);
        }
      } else if (this.hitEnemyArr.indexOf(enemy.node.uuid) !== -1) {
        this.hitEnemyArr.splice(this.hitEnemyArr.indexOf(enemy.node.uuid), 1);
      }
    });
  }
}
